#pragma once

#include <iostream>
#include <string>
#include <memory>
#include <cstring>
#include <cerrno>
#include <strings.h>
#include <functional>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Log.hpp"
#include "Common.hpp"
#include "InetAddr.hpp"
#include "ThreadPool.hpp"

using namespace LogModule;
using namespace ThreadPoolModule;

const static int gsockfd = -1;
const static uint16_t gdefaultport = 8080;

using adduser_t = std::function<void(InetAddr &id)>;
using delete_t = std::function<void(InetAddr &id)>;

using task_t = std::function<void()>;
using route_t = std::function<void(int sockfd, const std::string &message)>;

// 禁用拷贝
class nocopy
{
public:
    nocopy(){}
    nocopy(const nocopy &) = delete;
    const nocopy& operator = (const nocopy &) = delete;
    ~nocopy(){}
};

class UdpServer : public nocopy
{
public:
    UdpServer(uint16_t port = gdefaultport)
        : _sockfd(gsockfd), _addr(port), _isrunning(false)
    {}

    ~UdpServer()
    {
        if (_sockfd > gsockfd)
        {
            ::close(_sockfd);
        }
    }

    void InitServer()
    {
        // 1. 创建socket
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket: " << strerror(errno);
            Die(SOCKET_ERR);
        }
        LOG(LogLevel::INFO) << "socket success, sockfd is: " << _sockfd;

        // 2. bind网络信息到内核中
        int n = ::bind(_sockfd, _addr.NetAddr(), _addr.NetAddrLen());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind: " << strerror(errno);
            Die(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success";
    }

    void RegisterService(adduser_t adduser, delete_t deleteuser, route_t route)
    {
        _adduser = adduser;
        _deleteuser = deleteuser;
        _route = route;
    }

    void Start()
    {
        _isrunning = true;
        while (true)
        {
            char buffer[1024];
            struct sockaddr_in client;
            socklen_t len = sizeof(client);

            // 1. 接收客户端发来的消息
            ssize_t n = ::recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, CONV(&client), &len);
            if (n > 0)
            {
                buffer[n] = 0;
                InetAddr cli(client);
                std::string message;
                if (strcmp(buffer, " ...离线") == 0)
                {
                    // 2.1 删除用户
                    _deleteuser(cli);
                    message = cli.Addr() + "# " + buffer;
                }
                else
                {
                    // 2.2 新增用户
                    _adduser(cli);
                    message = cli.Addr() + "# " + buffer;
                }

                // 3. 构建转发任务, 推送给线程池, 让线程池进行转发
                task_t task = std::bind(UdpServer::_route, _sockfd, message);
                ThreadPool<task_t>::GetInstance()->Equeue(task);
            }
        }
        _isrunning = false;
    }

private:
    int _sockfd;
    InetAddr _addr;
    bool _isrunning;

    // 回调函数: 新增用户、删除用户
    adduser_t _adduser;
    delete_t _deleteuser;

    // 回调函数: 数据转发
    route_t _route;
};